import React, {Component} from 'react'
import {View, Text, SectionList, ActivityIndicator, StyleSheet, TouchableOpacity, Image} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import {connect} from 'react-redux'
import Enumeration, {STUDENT, TEACHER} from '../../config/enumeration'
import Badge from '../common/badge'
import {fetch_notifications, refresh_notifications, update_notification} from '../../redux/actions/notification'
import QuickFilter from '../common/quick_filter'
import DateTimePicker from 'react-native-modal-datetime-picker'
import styles from '../../config/styles'
import FormatDate from '../../helpers/timeFormat'
import AddNew from '../common/add_new'

class NotificationIndex extends Component {
    static navigationOptions = ({ navigation }) => {
        const params = navigation.state.params
        if (params != undefined) {
            const isTeacher = params.isTeacher == true
            const _headerRight = isTeacher  ?   (<TouchableOpacity 
                                                    style={{paddingRight: 5}}
                                                    onPress={() => navigation.navigate('new_notification')}
                                                >
                                                    <Text style={[styles.header_font]}>
                                                        新建通知
                                                    </Text>   
                                                </TouchableOpacity>) : <View />
            const _headerLeft = (
                <TouchableOpacity style={styles.header_left_time_picker} onPress={params.showDatePicker}>
                    <Text style={styles.header_font}>
                        选择时间
                    </Text>
                </TouchableOpacity>
            )                                    
           
            return {
                title: '通知',
                headerRight: <View />,
                headerLeft: _headerLeft,
            }
        }
      
       
    }

    constructor(props) {
        super(props)
        const notification = props.notification
        this.state = {
            section_notifications: [],
            initializing: true, //是否正在初始化，防止列表刚进来的时候就翻页
            loading: notification.loading,//列表状态，默认是加载中
            end_of_page: notification.end_of_page,//是否已经到底了
            locked: false, //点击一条数据的时候锁定列表，防止点击两下的时候触发两次
            current_page: notification.current_page,
            filter: null,
            created_at: null,
            pickingTime: false,
        };
    }


    componentWillMount () {
        this.fetch_notifications()
    }

    componentDidMount () {
        setTimeout(() => {this.setState({initializing: false})}, 1000)
        if (this.props.user.user.role == TEACHER) {
            this.props.navigation.setParams({isTeacher: true})         
        }
         //设定头部组件里面的时间选择
         this.props.navigation.setParams({
            showDatePicker: () => {
                this.setState({pickingTime: true})
            }
         })
    }

     //监控props的变化
     componentWillReceiveProps (nextProps) {
        if (nextProps.notification != undefined ) {
            const notification = nextProps.notification
            this.state.loading = false
            this.state.initializing = false
            this.state.current_page = notification.current_page
            this.state.end_of_page = notification.end_of_page
            this.transform_notifications_for_section(notification.notifications)  
            this.setState()
        }
    }

     //对数据进行转换
     transform_notifications_for_section = (notifications) => {
        let _transformation_data = {}
        this.state.section_notifications = []
        /* 
          同homeworks/index的转换方式
        */
        notifications.forEach((notification) => {
            if (_transformation_data[notification.created_date] == undefined) {
                _transformation_data[notification.created_date] = []
            }
            _transformation_data[notification.created_date].push(notification)
        })

        Object.keys(_transformation_data).forEach((key) => {
            let old_section_obj = this.state.section_notifications.filter((section_obj) => {
                return section_obj.title == key
            })
            if (old_section_obj.length == 0) {
                new_section_object = {
                    title: key,
                    data: _transformation_data[key]
                }
                this.state.section_notifications.push(new_section_object)
            } else {
                old_section_obj[0].data.push(..._transformation_data[key])
            }
        })
    }

    //获取作业
    fetch_notifications = () => {
        this.props.dispatch(fetch_notifications(this.state.filter))
    }

    //获取状态颜色
    _get_color_from = (status) => {
        switch (status) {
            case "未读":
                return "gray";
            case "已读":
                return "green";
            default:
                return "gray"
        }
    };

    //获取状态icon name
    _get_icon_area = (status) => {
        switch (status) {
            case "未读":
                return (<Icon name={"ios-undo-outline"} size={30} color="orange" />);
            case "已读":
                return (<Icon name={"ios-checkmark-outline"} size={40} color="gray" />);
            default:
                return (<Icon name={"ios-send-outline"} size={30}  color="gray"/>);
        }
    };

     //根据角色返回不一样的状态显示
     _status_bar_with_role = (role, item) => {
        //2是学生， 1和3是老师
        if (role == Enumeration.User.Role.Student) {
            const status = Enumeration.Notification.Status(item.status)
            const color = this._get_color_from(status);
            const icon_area = this._get_icon_area(status)
            return(
                <View>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center'}}>
                        <View style={{justifyContent: 'center'}}>
                            {icon_area}
                        </View>
                        <View style={{justifyContent: 'center'}}>
                            <Text style={[styles.text_label_grey,{color: color}]}>{status}</Text>
                        </View>
                    </View>
                </View>
            )
        } else {
            const readNotCount = item.assignno - item.answerno
            if ( readNotCount === 0 ) {
                return (
                        <View style={{flexDirection: 'row', justifyContent: 'center'}}>
                            <Icon name={"ios-checkmark-outline"} size={25} color="gray" />
                            <Text style={[styles.text_label_grey, {justifyContent: 'center'}]}>完成</Text>
                        </View>
                    )   
            } else {
                return (
                    <View>
                        <View>
                            <Text style={[styles.text_label_grey, {color: 'green'}]}>未读: {readNotCount}</Text>
                        </View>
                        <View>
                            <Text style={[styles.text_label_grey, {color: 'gray'}]}>已读: {item.answerno}</Text>
                        </View>
                    </View>
                )
            }
        }
    }

    //翻页
    _flip = () => {
        if (this.state.initializing || this.state.loading)
            //正在初始化或者正在读取数据的时候直接return
            return
        else if (this.state.end_of_page) {
            Toast.show('没有更多数据了')
        } else {
            this.fetch_notifications()
        }
    }

    //用于sectionlist的key
    _keyExtractor = (item, index) => index

    //跳转动作
    _link_to_show = (item, target_component) => {
        if (this.state.locked) {
            return false
        } else {
            this.props.navigation.navigate(target_component, {id: item.id})
            this.state.locked = true
            setTimeout(() => {this.state.locked = false}, 200)
            this.props.dispatch(update_notification(item.id, {status: true}))
        }
    };

    //刷新列表
    _refresh = () => {
        this.props.dispatch(refresh_notifications(this.state.filter))        
    }

    //筛选状态
    _filter_notifications = (filter) => {
        if (this.state.initializing || this.state.loading)
            return false
        else {
            this.setState({filter: filter, initializing: true, created_at: null}, () => {
                this.props.dispatch(refresh_notifications(filter, ""))
            })
        }     
    }

     //筛选时间
     filterTime = (time) => {
        if (this.state.initializing || this.state.loading)
            return
        else {
            this.setState({
                created_at: FormatDate(time),
                pickingTime: false, 
                initializing: true,
                filter: null
            }, () => {
                this.props.dispatch(refresh_notifications(null, time))
            })
        } 
    }

    //分组后的header
    _sectionHeader = (item) => {
        return(
            <View style={styles.section_header_container}>
                <Text style={styles.section_header_text}>
                    {item.section.title}
                </Text>
            </View>
        ) 
    };


     //头部组件
     _headerComponent = () => {
        var role = this.props.user.user.role //2是学生， 1和3是老师
        return (
            <View style={{flexDirection: 'row', height: 40, backgroundColor: 'white'}}>
                <QuickFilter
                    onPress={() => {this._filter_notifications('all')}}
                    active={["all", null].includes(this.state.filter)}
                    activeIconName={'ios-crop'}
                    unactiveIconName={'ios-crop-outline'}
                    filterName={'全部'}
                />
                <QuickFilter
                    onPress={() => {this._filter_notifications('unread')}}
                    active={this.state.filter == 'unread'}
                    activeIconName={'ios-undo'}
                    unactiveIconName={'ios-undo-outline'}
                    filterName={'未读'}
                />
                <QuickFilter
                    onPress={() => {this._filter_notifications('read')}}
                    active={this.state.filter == 'read'}
                    activeIconName={'ios-create'}
                    unactiveIconName={'ios-create-outline'}
                    filterName={'已读'}
                />
                 <DateTimePicker
                    isVisible={this.state.pickingTime}
                    onConfirm={(date) => this.filterTime(FormatDate(date))}
                    onCancel={() => this.setState({pickingTime: false})}
                    date={this.state.created_at ? new Date(this.state.created_at) : new Date()}
                    cancelTextIOS={'取消'}
                    confirmTextIOS={'确定'}
                    titleIOS={'选择日期'}
                />
            </View>
        )
    };

    //尾部组件
    _footerComponent = () => {
        let text
        if (this.state.end_of_page) {
            text = '已经没有数据了'
        } else {
            text = '正在加载数据...'
        }
        return (
            <View style={{alignItems: 'center', backgroundColor: '#f6f6f6'}}>
                <Text>{text}</Text>
            </View>
        )
    };

    //每一条item的渲染模板
    _renderItem = (section) => {
        const role = this.props.user.user.role //2是学生， 1和3是老师
        const item = section.item
        //这里需要根据角色来跳转不同的页面
        const target_component = role == Enumeration.User.Role.Student ? 'notifications_show' : 'notifications_correcting'
    
        return(
            <TouchableOpacity
                style={styles.list_item_container}
                onPress={() => {this._link_to_show(item, target_component)}}
            >
                <View style={{flex: 1, flexDirection: 'row', borderBottomColor: 'grey'}}>
                    <View style={{flex: 1}}>
                        <View style={{flexDirection: 'row'}}>
                            {item.if_has_attachments ? <Icon name={'ios-attach'} size={20} /> : null}
                            <Text 
                                style={styles.list_item_text} 
                                numberOfLines={1}
                            >
                                {item.title}
                            </Text>
                        </View>
                        <Text style={styles.text_label_grey}>{item.teacher}</Text>
                    </View>
                        {this._status_bar_with_role(role, item)}
                </View>
            </TouchableOpacity>
        )
    };

    render () {
        const {user, navigation} = this.props
        return (
            <View style={styles.main_body}>
                {this._headerComponent()}
                <SectionList
                    keyExtractor={this._keyExtractor}
                    renderSectionHeader={this._sectionHeader}
                    //ListHeaderComponent={this._headerComponent}
                    ListFooterComponent={this._footerComponent}                 
                    renderItem={this._renderItem}
                    extraData={this.props}
                    sections={this.state.section_notifications}
                    onRefresh={this._refresh}
                    refreshing={this.state.loading}
                    onEndReachedThreshold={0.1}
                    onEndReached={this._flip.bind(this)}
                    stickySectionHeadersEnabled={true}
                    ItemSeparatorComponent={() => {return (<View style={{height: 5}} />)}}     
                    SectionSeparatorComponent={() => {return (<View style={{height: 5}} />)}}
                    style={{flex: 1}}       
                />
                 {user.user.role == TEACHER ? (
                    <AddNew onPress={() => {navigation.navigate('new_notification')}} />) 
                    : 
                    null
                }
            </View>
        )
    }
}


const mapStateToProps = (state) => {
    return {
        user: state.user,
        notification: state.notification
    }
}

export default connect(mapStateToProps)(NotificationIndex)